//
//  CHLoginViewController.m
//  CarFile
//
//  Created by 陈浩 on 2017/3/20.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHLoginViewController.h"
#import "CHTabBarController.h"
#import "CH_TabBarViewController.h"
#import "CHAddressController.h"
#import "DESCript.h"
#import <CoreLocation/CoreLocation.h>
#import "ProvinceModel.h"
#import "SectionGroupModel.h"
#import "CHNavigationController.h"


//henan
//120123a

@interface CHLoginViewController ()<UIAlertViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;    //  定位服务
@property (nonatomic ,strong) NSMutableArray *citys;
@property (nonatomic ,strong) NSMutableArray *groups;
@property (nonatomic ,strong) UIButton *postionBtn;

@property (weak, nonatomic) IBOutlet UIView *usernameView;
@property (weak, nonatomic) IBOutlet UIView *pwdView;


@property (weak, nonatomic) IBOutlet UITextField *usernameField;
@property (weak, nonatomic) IBOutlet UIButton *refusedBtn;
@property (weak, nonatomic) IBOutlet UITextField *pwdField;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *pwdStyeBtn;
@property (nonatomic ,strong) UIAlertView *alertView;
@property (nonatomic ,copy) NSString *remarksPath;
- (IBAction)pwdStyeBtnClick:(UIButton *)btn;
- (IBAction)refusedBtnClick:(UIButton *)btn;

- (IBAction)loginBtnClick:(UIButton *)btn;



@end

@implementation CHLoginViewController

-(NSMutableArray *)groups{
    if (!_groups) {
        _groups = [NSMutableArray array];
    }
    return _groups;
}


-(NSMutableArray *)citys{
    if (!_citys) {
        _citys = [NSMutableArray array];
    }
    return _citys;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"登录";
    
    //    检查是否需要更新版本
    [self checkVersion];
    
    [self getData];
    //      开启定位
//    [self locationStart];
    
    //
//        self.usernameField.text = @"henan";
//        self.pwdField.text = @"120123a";
    

    
    self.usernameView.backgroundColor = [UIColor colorWithHexString:@"098EDD" alpha:0.1f];
    self.usernameView.layer.cornerRadius = 7.5;
    self.usernameView.layer.masksToBounds = YES;
    
    self.pwdView.backgroundColor = [UIColor colorWithHexString:@"098EDD" alpha:0.1f];
    self.pwdView.layer.cornerRadius = 7.5;
    self.pwdView.layer.masksToBounds = YES;
    
   
    self.refusedBtn.hidden = YES;
    [self.pwdField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.pwdField.secureTextEntry = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"098edd" alpha:1.0f];
    self.loginBtn.layer.cornerRadius = 5;
    self.loginBtn.layer.masksToBounds = YES;
    
    [self setupLeftBarButtonItem];
    
}



-(void)setupLeftBarButtonItem{
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 21)];
    btn.titleLabel.font = Font(16);
    [btn setImage:[UIImage imageNamed:@"login_pull"] forState:UIControlStateNormal];
    NSString *cityname =   (NSString *)[Util getValue:@"cityname"];
    if (cityname.length > 0) {
        [btn setTitle:cityname forState:UIControlStateNormal];
    }else{
        [btn setTitle:@"切换地区" forState:UIControlStateNormal];
    }
   
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    // 重点位置开始
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, btn.titleLabel.w + 65, 0, -btn.titleLabel.w - 65);
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, -btn.currentImage.size.width, 0, btn.currentImage.size.width);
    // 重点位置结束
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btn addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.postionBtn = btn;

}


-(void)leftBarButtonItemClick{
    
    CHAddressController *addressVc = [[CHAddressController alloc] init];
    addressVc.sectionArr = [NSArray arrayWithArray:self.groups];
    addressVc.block = ^(ProvinceModel *model) {
        [self.postionBtn setTitle:model.name forState:UIControlStateNormal];
        [Util setObject:model.baseurl key:@"baseurl"];
        if ([model.name isEqualToString:@"浙江"]) {
            [Globle getInstance].user = @"cheweixiuG";
            [Globle getInstance].key = @"G#YL%*C_";
        }else{
            [Globle getInstance].user = USER;
            [Globle getInstance].key = KEY;
        }
    };
    CHNavigationController *nav = [[CHNavigationController alloc] initWithRootViewController:addressVc];
    [self presentViewController:nav animated:YES completion:NULL];
    

    
}


//
////开始定位
//-(void)locationStart{
//    //判断定位操作是否被允许
//
//    if([CLLocationManager locationServicesEnabled]) {
//        self.locationManager = [[CLLocationManager alloc] init] ;
//        self.locationManager.delegate = self;
//        //设置定位精度
//        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
//        if (IOS8) {
//            //使用应用程序期间允许访问位置数据
//            [self.locationManager requestWhenInUseAuthorization];
//        }
//        // 开始定位
//        [self.locationManager startUpdatingLocation];
//    }else {
//        //提示用户无法进行定位操作
//        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
//
//    }
//}
//#pragma mark - CoreLocation Delegate
//
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//
//{
//    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
//    [self.locationManager stopUpdatingLocation];
//    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
//    CLLocation *currentLocation = [locations lastObject];
//
//    //获取当前所在的城市名
//    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//    //根据经纬度反向地理编译出地址信息
//    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
//     {
//         if (array.count >0)
//         {
//             CLPlacemark *placemark = [array objectAtIndex:0];
//             //获取省份
//             NSString *currCity = placemark.administrativeArea;
////             if (!currCity) {
////                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
////                 currCity = placemark.administrativeArea;
////
////             }
////             [self.postionBtn setTitle:currCity forState:UIControlStateNormal];
//
//         } else if (error ==nil && [array count] == 0)
//         {
//             NSLog(@"No results were returned.");
//         }else if (error !=nil)
//         {
//             NSLog(@"An error occurred = %@", error);
//         }
//
//     }];
//
//}
//
//
//- (void)locationManager:(CLLocationManager *)manager
//       didFailWithError:(NSError *)error {
//    if (error.code ==kCLErrorDenied) {
//        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
//    }
//
//}



- (void)textFieldDidChange:(UITextField *)textField {
    
    self.refusedBtn.hidden = textField.text.length >0 ? NO :YES;
    
    
}






- (IBAction)loginBtnClick:(id)sender {
    
    if (self.usernameField.text == nil || self.usernameField.text.length == 0) {
        [MBProgressHUD showTipMessageInWindow:@"用户名不能为空"];
    }else if(self.pwdField.text == nil || self.pwdField.text.length == 0 ){
        
        [MBProgressHUD showTipMessageInWindow:@"密码不能为空"];
        
    }else{
        //       登录
        [self login];
        
    }
    
}



-(void)login{

    [self.view endEditing:YES];
    
   NSString *cityname =   (NSString *)[Util getValue:@"cityname"];
    if (cityname == nil || cityname.length == 0) {
        [MBProgressHUD showWarning:@"请选择所在省份!"];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在登录···"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//        params[@"areaid"] = @"410100000000000000";
    params[@"userflag"] = self.usernameField.text;
    params[@"password"] = [DESCript encrypt:self.pwdField.text encryptOrDecrypt:kCCEncrypt key:@"s(p7~;j^"];
    params[@"user"] = [Globle getInstance].user;
    NSString *sign = [DESCript encrypt:self.usernameField.text encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"sign"] = sign;
    NSLog(@"%@",params);
    [[Globle getInstance].service requestWithServiceName:@"lcipapplogin" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [MBProgressHUD hideHUD];
        if (result) {
            NSLog(@"%@",result);
            if ([result[@"code"] isEqualToString:@"1"]) {
                
                // 获取用户类型
                NSString *usertype = result[@"data"][@"usertype"];
                
                [Globle getInstance].userInfoDic = result[@"data"];
                [Util setBool:YES key:@"islogin"];
                [Util setObject:self.usernameField.text key:@"userflag"];
                [Util setObject:self.pwdField.text key:@"pwd"];
                [Util setObject:result[@"data"][@"areaid"] key:@"areaid"];
                [Util setObject:result[@"data"][@"usertype"] key:@"usertype"];
                [Util setObject:result[@"data"][@"areacn"] key:@"areacn"];
                [Util setObject:sign key:@"sign"];
                
               
              
                
                // options是动画选项
                [UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:0.5f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                    BOOL oldState = [UIView areAnimationsEnabled];
                    [UIView setAnimationsEnabled:NO];
                    if ([usertype isEqualToString:@"99"]) {
                        [UIApplication sharedApplication].keyWindow.rootViewController = [[CH_TabBarViewController alloc] init];
                    }else{
                        [UIApplication sharedApplication].keyWindow.rootViewController = [[CHTabBarController alloc] init];
                    }
         
                    [UIView setAnimationsEnabled:oldState];
                } completion:^(BOOL finished) {
                    
                }];
                
            }else{
                
                [MBProgressHUD showError:result[@"status"]];
            }
            
        }
        
    }];
    
}


- (IBAction)pwdStyeBtnClick:(UIButton *)btn {
    btn.selected = !btn.selected;
    
    self.pwdField.secureTextEntry = btn.selected ? NO : YES;
    
}

- (IBAction)refusedBtnClick:(UIButton *)btn {
    
    self.pwdField.text = nil;
    btn.hidden = YES;
    
}


#pragma mark 检查版本
-(void)checkVersion
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:leapAPPname forKey:@"appname"];
    
    [[Globle getInstance].service RequestWithServiceName:@"lbcp_getAppVersion" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = (NSDictionary *)result;
        if(nil != dic)
        {
            [MBProgressHUD hideHUD];
            //获取本地版本
            self.remarksPath = dic[@"remarks"];
            NSString *localVersion = VersionCode;
            int localVersionNUm = (localVersion == nil ? -1 : [localVersion intValue]);
            //获取服务器版本
            NSString *serverVersion = [dic valueForKey:@"appversion"];
            int serverVersionNum = (serverVersion == nil ? -1 : [serverVersion intValue]);
            //判断是非升级
            if(localVersionNUm < serverVersionNum)
            {
                NSString *upgrade = [dic valueForKey:@"upgrade"];
                if([@"1" isEqualToString:upgrade])    //   强制升级
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                }
                else
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
                }
                
                [self.alertView show];
                
            }
        }
    }];
    
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == self.alertView)
    {
        if(buttonIndex == 0)
        {
            NSString *urlStr = [NSString stringWithFormat:@"%@",self.remarksPath];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
    }
}



-(void)getData{

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"user"] = USER;
    params[@"sign"] = [DESCript encrypt:USER encryptOrDecrypt:kCCEncrypt key:KEY];

    [[Globle getInstance].service requestWithServiceName:@"appsearchpromenue" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"%@",result);
        if ([result[@"code"] isEqualToString:@"1"]) {
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                ProvinceModel *model = [ProvinceModel objectWithKeyValues:dict];
                [self.citys addObject:model];
                
//                 获取拼音首字母
                NSString *pinyin =   [self Charactor:model.name getFirstCharactor:YES];
                
                [arr addObject:pinyin];
            }
           //       字母排序
            NSArray *newArray = [arr sortedArrayUsingSelector:@selector(compare:)];
           //   去除重复元素 ，获取索引数组
            NSMutableArray *listAry = [[NSMutableArray alloc]init];
            for (NSString *str in newArray) {
                if (![listAry containsObject:str]) {
                    [listAry addObject:str];
                }
            }
 
            for (int i = 0; i< listAry.count; i++) {
                SectionGroupModel *groupModel = [[SectionGroupModel alloc] init];
                groupModel.firstLetter = listAry[i];
                for (int j =0; j < self.citys.count; j++) {
                    ProvinceModel *model = self.citys[j];
                    //  获取拼音首字母
                    NSString *firstLetter =   [self Charactor:model.name getFirstCharactor:YES];
                    if ([firstLetter isEqualToString:groupModel.firstLetter]) {
                        [groupModel.provinces addObject:model];
                      
                    }
                }
                [self.groups addObject:groupModel];
                
            }
        }
    }];
}


- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str capitalizedString];
    //转化为大写拼音
    if(isGetFirst)
    {
        //获取并返回首字母
        return [pinYin substringToIndex:1];
    }
    else
    {
        return pinYin;
    }
}





@end
